import { ref, computed } from 'vue';
import u from "./fieldUtils.js";

const fieldExtends = {

};

export function extendFieldModel(fieldModel) {
  let fieldModelValue = fieldModel.value;
  const { control } = fieldModelValue.meta;
  if (control && (fieldExtends[control])) {
    fieldExtends[control].extend(fieldModelValue);
  }
  fieldModel.value = fieldModelValue;
}

export default function (vm, model, meta) {
  let modelData = model.value;

  const attr = meta.name;
  const value = computed({
    get() {
      return u.get(meta, model.value);
    },
    set(newValue) {
      u.set(meta, model.value, newValue);
    }
  });

  const displayValue = computed(() => {
    return modelData.data[attr] == null ? "~" : modelData.data[attr];
  });

  const visible = computed(() => {
    return (meta.visible == null || meta.visible == true)
      && vm.getState(META.value);
  });

  const isEditing = computed(() => {
    if (model.value.mode == "browse") {
      return false;
    } else {
      if (meta.readonly == true) {
        return false;
      } else {
        return true;
      }
    }
  });

  const fieldModel = ref({
    meta,
    title: meta.title,
    visible,
    isEditing,
    value,
    displayValue,
    setState: function (attr, attrValue) {
      let fieldModelValue = fieldModel.value;
      fieldModelValue[attr] = attrValue;
      fieldModel.value = fieldModelValue;
    },
    getValue: function () {
      return u.get(meta, model.value);
    }, setValue: function (newValue) {
      u.set(meta, model.value, newValue);
    }
  });

  extendFieldModel(fieldModel);
  return fieldModel;
}